package com.czy;

import com.czy.model.Request;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author czy
 * @date 2021-5-24 18:21
 */
public class TomcatServer {
    public static void main(String[] args) throws IOException {
        // 在端口上创建一个服务器套接字
        ServerSocket serverSocket = new ServerSocket(8000);
        System.out.println("服务启动成功");

        //当服务没有关闭时
        while (!serverSocket.isClosed()){
            // 监听来自客户端的连接
            Socket socket = serverSocket.accept();

            System.out.println("有客户端连接了: "+socket);
            handler(socket);
        }
    }

    private static void handler(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        Request request = new Request(inputStream);
        OutputStream outputStream = socket.getOutputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
        String line = null;
        int count=0;
        while ((line=bufferedReader.readLine())!=null){
            System.out.println("接收到客户端的数据: "+line);
            if (count==0){
                String[] oneLine = line.split(" ");
                System.out.println("请求方式: "+oneLine[0]);
                System.out.println("请求资源: "+oneLine[1]);
                System.out.println("请求协议: "+oneLine[2]);
            }
            count++;
        }
        //返回outputstream，主体内容是OK
        String resp="HTTP/1.1 200+\r\n"+"Content-Type：text/html+\r\n"
                +"\r\n"+"OK";
        System.out.println(resp);
        outputStream.write(resp.getBytes());
        outputStream.flush();
        outputStream.close();
        socket.close();
    }
}
